package com.kim.resource.client.controller;

import com.kim.oauth.common.util.UserUtils;
import org.springframework.security.access.annotation.Secured;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.security.RolesAllowed;
import javax.servlet.http.HttpServletRequest;
import java.security.Principal;
import java.util.HashMap;
import java.util.Map;

/**
 * 获取用户认证相信4种方式
 */
@RestController
public class UserController {

    /**
     * 用户认证信息工具类
     */
    private final UserUtils userUtils;

    public UserController(UserUtils userUtils) {
        this.userUtils = userUtils;
    }

    @GetMapping("/user1")
    public Object user1(Principal principal) {
        return principal;
    }

    @GetMapping("/user2")
    public Object user2(Authentication authentication) {
        return authentication;
    }

    @GetMapping("/user3")
    public Object user3(HttpServletRequest request) {
        return request.getUserPrincipal();
    }

    @GetMapping("/user4")
    public Object user4() {
        return SecurityContextHolder.getContext().getAuthentication();
    }

    /**
     * TOKEN 获取用户认证信息
     */
    @GetMapping("/tokenInfo")
    public Map tokenInfo() {
        Map<String, Object> result = new HashMap<>(8);
        result.put("id", userUtils.getCurrentAuthenticationUserId());
        result.put("authorities", userUtils.getCurrentAuthorities());
        result.put("password", userUtils.getCurrentAuthenticationPwdSet());
        result.put("username", userUtils.getCurrentAuthenticationUsername());
        result.put("phone", userUtils.getCurrentAuthenticationPhone());
        return result;
    }

    @GetMapping("/user5")
    public Object user5() {
        return SecurityContextHolder.getContext().getAuthentication();
    }

    @GetMapping("/user6")
    public Object user6() {
        return SecurityContextHolder.getContext().getAuthentication();
    }


    @Secured("ROLE_SURGE_ADMIN")
    @GetMapping("/user7")
    public Object user7() {
        return SecurityContextHolder.getContext().getAuthentication();
    }

    @PreAuthorize("hasRole('ROLE_SURGE_ADMIN')")
    @GetMapping("/user8")
    public Object user8() {
        return SecurityContextHolder.getContext().getAuthentication();
    }

    @RolesAllowed("ROLE_SURGE_USER")
    @GetMapping("/user9")
    public Object user9() {
        return SecurityContextHolder.getContext().getAuthentication();
    }

}
